const express = require('express');
const router = express.Router();
const { sendMail } = require('../config/email');
const Email = require('../models/Email');
const ScheduledEmail = require('../models/ScheduledEmail');
const { Op } = require('sequelize');
const sequelize = require('../config/database');
const emailScheduler = require('../services/scheduler');

// 私发邮件路由
router.post('/send-private-email', async (req, res) => {
    try {
        const { to, content } = req.body;
        
        // 创建邮件记录
        const emailRecord = await Email.create({
            to,
            subject: '你收到了一封私密邮件',
            content,
            type: 'private',
            status: 'pending'
        });

        // 发送邮件
        await sendMail({
            to,
            subject: '你收到了一封私密邮件',
            message: content
        });

        // 更新发送状态
        await emailRecord.update({
            status: 'sent',
            sendTime: new Date()
        });

        res.json({ success: true, message: '邮件发送成功' });
    } catch (error) {
        console.error('邮件发送失败:', error);
        
        // 如果邮件记录存在，更新失败状态
        if (emailRecord) {
            await emailRecord.update({ status: 'failed' });
        }

        res.status(500).json({ 
            error: '邮件发送失败',
            message: error.message 
        });
    }
});

// 获取邮件发送历史
router.get('/history', async (req, res) => {
    try {
        const emails = await Email.findAll({
            order: [['createdAt', 'DESC']],
            limit: 50
        });
        res.json(emails);
    } catch (error) {
        console.error('获取历史记录失败:', error);
        res.status(500).json({ error: '获取历史记录失败' });
    }
});

// 修改定时邮件发送路由
router.post('/schedule-email', async (req, res) => {
    try {
        const { to, content, scheduleTime } = req.body;

        if (!to || !content || !scheduleTime) {
            return res.status(400).json({ error: '缺少必要参数' });
        }

        // 验证时间是否合法（必须是未来时间）
        const scheduledTime = new Date(scheduleTime);
        if (scheduledTime <= new Date()) {
            return res.status(400).json({ error: '定时发送时间必须是未来时间' });
        }

        // 使用调度器创建定时邮件
        const scheduledEmail = await emailScheduler.addEmail({
            to,
            content,
            scheduleTime: scheduledTime,
            status: 'pending'
        });

        res.json({ 
            success: true, 
            message: '邮件已安排定时发送',
            scheduledId: scheduledEmail.id 
        });
    } catch (error) {
        console.error('安排定时邮件失败:', error);
        res.status(500).json({ error: '安排定时邮件失败' });
    }
});

// 添加邮件发送速率限制
const rateLimit = {
    windowMs: 60 * 60 * 1000, // 1小时窗口
    maxRequests: 20, // 最大请求次数
    requests: new Map()
};

// 速率限制中间件
function rateLimiter(req, res, next) {
    const ip = req.ip;
    const now = Date.now();
    
    if (!rateLimit.requests.has(ip)) {
        rateLimit.requests.set(ip, []);
    }
    
    // 清理过期的请求记录
    const requests = rateLimit.requests.get(ip).filter(time => 
        now - time < rateLimit.windowMs
    );
    
    if (requests.length >= rateLimit.maxRequests) {
        return res.status(429).json({ 
            error: '发送频率过高',
            message: '请稍后再试' 
        });
    }
    
    requests.push(now);
    rateLimit.requests.set(ip, requests);
    next();
}

// 应用速率限制到所有邮件发送路由
router.use(rateLimiter);

module.exports = router; 